package logic

import (
	"context"
	"errors"
	"fresh-box/freshrpc/freshrpc"
	"fresh-box/freshrpc/internal/svc"
	"fresh-box/model/mysql"
	"github.com/zeromicro/go-zero/core/logx"
)

type FreshAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFreshAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FreshAddLogic {
	return &FreshAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FreshAddLogic) FreshAdd(in *freshrpc.FreshAddRequest) (*freshrpc.FreshAddResponse, error) {
	// todo: add your logic here and delete this line
	var good mysql.Fresh
	begin := mysql.DB.Begin()
	err := good.GoodShow(begin, in.Name)
	if err == nil {
		begin.Rollback()
		return nil, errors.New("商品名称已存在")
	}
	var types mysql.Type
	err = types.TypeShow(begin, in.Types)
	if err != nil {
		types = mysql.Type{
			Typename: in.Types,
		}
		err = types.TypeAdd(begin)
		if err != nil {
			begin.Rollback()
			return nil, errors.New("添加失败")
		}
	}
	fresh := &mysql.Fresh{
		Name:    in.Name,
		Price:   in.Price,
		TypesId: int(types.ID),
	}
	err = fresh.FreshAdd(begin)
	if err != nil {
		begin.Rollback()
		return nil, errors.New("添加失败")
	}
	begin.Commit()
	return &freshrpc.FreshAddResponse{
		FreshId: int64(fresh.ID),
	}, nil
}
